package de.mizi.utility;

import java.awt.Color;
import java.awt.Font;
import java.awt.Rectangle;
import java.awt.font.FontRenderContext;
import java.awt.font.TextLayout;
import java.awt.geom.Rectangle2D;

/**
 * This class holds all the data thats often used by the renderer classes
 * of this game.
 * @author mizi
 *
 */
public class FontData {
	public final Font font;
	public final Color fontColor;
	public final FontRenderContext fontRenderContext;
	public final int width;
	public final int height;
	public final int xCenter;
	public final int yOffset;
	
	/**
	 * Construct a new FontData object with the given font and font color.
	 * @param font the font
	 * @param fontColor the font color
	 */
	public FontData(Font font, Color fontColor) {
		this.font = font;
		this.fontColor = fontColor;
		this.fontRenderContext = new FontRenderContext(font.getTransform(), false, false);
		TextLayout layout;
		Rectangle bounds = new Rectangle();
		Rectangle2D temp;
		int minY = 0;
		// Determine the maximum width and height, as well as the minimum
		// y-offset of the ASCII chars.
		// (Maybe this has not the best performance, but it is only done
		//  once, so that should be okay.)
		for(char c = 0; c <= 128; ++c) {
			layout = new TextLayout("" + c, this.font, fontRenderContext);
			temp = layout.getBounds();
			bounds.width = Math.max(bounds.width, (int)temp.getWidth());
			bounds.height = Math.max(bounds.height, (int)temp.getHeight());
			minY = Math.min(minY, (int)temp.getMinY());
		}
		this.width = bounds.width;
		this.height = bounds.height;
		this.xCenter = width / 2;
		this.yOffset = minY;
	}
	
	/**
	 * Get the width of the given glyph.
	 * @param glyph the glyph
	 * @return the width of the glyph
	 */
	public int getGlyphWidth(char glyph) {
		return (int)font.getStringBounds("" + glyph, fontRenderContext).getWidth();
	}
	
	/**
	 * Get the bounds of the given string.
	 * @param str the string
	 * @return the bounds of the string
	 */
	public Rectangle2D getStringBounds(String str) {
//		return new TextLayout(str, font, fontRenderContext).getBounds();
		// TextLayout has the better results, but it seems to be much slower.
		return font.getStringBounds(str, fontRenderContext);
	}
}
